import { useState, useEffect } from 'react'
import { Button, Form, Input, message } from 'antd'
import axios from 'axios'
import Layout from '../../components/layout'
import { API } from '../../config'
import { Auth } from '../../store/models/auth'
import { isAuth } from '../../utils/auth'

export default function CreateCategory() {
  const [name, setName] = useState('')

  const {
    user: { _id },
    token,
  } = isAuth() as Auth

  useEffect(() => {
    async function insertCategory() {
      try {
        const res = await axios.post<{ name: string }>(
          `${API}/category/create/${_id}`,
          {
            name: name,
          },
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        )
        message.success(`分类 ${res.data.name} 添加成功`)
      } catch (err) {
        message.error({
          key: 'create-category-error',
          content: err.response.data.error,
        })
      }
    }
    name && insertCategory()
  }, [name, _id, token])

  function onFinish(values: { name: string }) {
    setName(values.name)
  }

  const indent = 3

  return (
    <Layout title='Create Category'>
      <Form
        labelCol={{
          span: indent,
        }}
        onFinish={onFinish}
      >
        <Form.Item label='Category Name' name='name'>
          <Input type='text' />
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: indent,
          }}
        >
          <Button type='primary' htmlType='submit'>
            Create Category
          </Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}
